package com.hundsun.yr.universal.p2p.ui.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper.UpdateItem;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.utils.HsNumberUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog.HSDialogOnItemClickListener;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView.OnLoadMoreListener;
import com.hundsun.yr.universal.library.widget.HSSwipeRefreshLayout;
import com.hundsun.yr.universal.p2p.bean.Invested;
import com.hundsun.yr.universal.p2p.bean.MyLoanListBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.BaseListEntityPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.LoanDetailActivity;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @version V1.0
 * @Title: ApplyInFragment.java
 * @Description: 我的借款-全部
 * @date 2016-1-5 下午2:51:14
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class ApplyInFragment extends BaseFragment implements BaseListView,
        OnRefreshListener, OnItemClickListener, OnLoadMoreListener, UpdateItem<MyLoanListBeen>, HSDialogOnItemClickListener {

    private RequestPresenter mPresenter = null;
    /**
     * 下拉容器
     **/
    private HSSwipeRefreshLayout hsSwipeRefreshLayout_already = null;
    /**
     * listview 适配器
     **/
    private HolderAdapter<MyLoanListBeen> mAdapter = null;
    /**
     * 可以加载更多的listview
     **/
    private HSLoadMoreListView lv_already = null;
    /**
     * 数据集合
     **/
    private List<MyLoanListBeen> data = new ArrayList<MyLoanListBeen>();
    private String zwgt_data;

    @Override
    protected void onFirstUserVisible() {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_already.setRefreshing(true);
        mPresenter = new BaseListEntityPresenterImpl(mContext, this, Invested.BASEKEY);
        //新的查询我的投资
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.LOAN_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.LOAN_LIST,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.LOAN_LIST,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    @Override
    protected void onUserVisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onUserInvisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_already = findView(R.id.hsSwipeRefreshLayout_applyin);
        return hsSwipeRefreshLayout_already;
    }

    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        if (mPresenter == null) {
            mPresenter = new BaseListEntityPresenterImpl(mContext, this, Invested.BASEKEY);
        }

        mPresenter.initialized();

        if (hsSwipeRefreshLayout_already == null) {
            hsSwipeRefreshLayout_already = findView(R.id.hsSwipeRefreshLayout_applyin);
        }

        ViewCreatorHelper<MyLoanListBeen> creatorHelper = new ViewCreatorHelper<MyLoanListBeen>(R.layout.item_my_loan_all, this);
        mAdapter = new HolderAdapter<MyLoanListBeen>(mContext, creatorHelper.viewCreator());

        lv_already = findView(R.id.lv_applyin);
        lv_already.setOnItemClickListener(this);
        lv_already.setAdapter(mAdapter);

        hsSwipeRefreshLayout_already.setOnRefreshListener(this);
        lv_already.setOnLoadMoreListener(this);
    }


    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.frag_apply_in;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub
    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return false;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void refreshListData(List<T> result) {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_already.setRefreshing(false);
        if (data.size() > 0) data.clear();
        if (result != null) {
            data.addAll((Collection<? extends MyLoanListBeen>) result);
            lv_already.setLoadMoreEnabled(result.size() == Constants.PAGESIZE_MIDDLE);
        }
        mAdapter.update(data);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void addMoreListData(List<T> result) {
        lv_already.onLoadMoreComplete();
        if (result != null) {
            data.addAll((Collection<? extends MyLoanListBeen>) result);
            mAdapter.update(data);
            lv_already.setLoadMoreEnabled(result.size() == Constants.PAGESIZE_MIDDLE);
        }
    }

    @Override
    public <T> void onFailure(String task_name) {
        hsSwipeRefreshLayout_already.setRefreshing(false);
        lv_already.onLoadMoreComplete();
        if (data.size() > 0) data.clear();
        lv_already.setAdapter(mAdapter);
        mAdapter.update(data);
    }

    // TODO: 2017/5/23 apply_progress  prd_progress 没有完全搞明白
    @Override
    public void refreshItem(View view, int position, final MyLoanListBeen invest) {
        /**还款利率**/
        TextView tv_annualincome = findView(view, R.id.tv_annualincome);
        if (!invest.debt_rate.isEmpty()){
            tv_annualincome.setText(CommTool.keep1Digits(new BigDecimal(invest.debt_rate)) + "%");
        } else {
            tv_annualincome.setText(CommTool.keep1Digits(new BigDecimal(0)) + "%");
        }


        /**营销商品名称**/
        TextView tv_title = findView(view, R.id.tv_title);
        if (invest.prdname != null && !invest.prdname.isEmpty()) {
            tv_title.setText(invest.prdname);
        } else {
            tv_title.setText("申请编号" + invest.uuid);
        }

        /**募集总额|申请金额**/
        TextView tv_income = findView(view, R.id.tv_income);
        tv_income.setText(HsNumberUtils.moneyTenThousandsFormat(Double.valueOf(invest.amount)));

        /**募集状态**/
        TextView tv_prd_progress = findView(view, R.id.tv_prd_progress);
        tv_prd_progress.setText(invest.getPrdprogress());

        /**还款方式  右下**/
        TextView tv_incomemonet = findView(view, R.id.tv_incomemonet);

        /**下一期还款额度  右下**/
        TextView tv_next_amount = findView(view, R.id.tv_next_amount);

        /**撤销按钮  右中**/
        HSButton btn_cancel = findView(view, R.id.btn_prd_progress);

        /**募集总额|申请金额  中**/
        TextView tv_raise_amount = findView(view, R.id.tv_raise_amount);

        /**还款进度|借款期限  左下**/
        TextView tv_invset_money = findView(view, R.id.tv_invset_money);

        /**下期还款  右下  偏上**/
        TextView tv_next_term = findView(view, R.id.tv_next_term);

        /**
         * 0	用户草稿
         1	一审（风控）审批中
         2	二审（运营）审批中
         10	审批完成，已转产品。
         100	用户撤回
         110	一审（风控）拒绝
         120	二审（运营）拒绝
         */
        if (TextUtils.equals(invest.applyprogress, "0")) {
            //用户草稿  显示：还款方式，撤销按钮，申请金额，借款期限    ；隐藏：下期还款金额，募集状态，募集总额，还款进度，下期还款日
            /**设置还款方式**/
            tv_incomemonet.setVisibility(View.VISIBLE);
            tv_incomemonet.setText(invest.getPayMethod(mContext));
            /**下期返款金额**/
            tv_next_amount.setVisibility(View.GONE);
            /**募集状态**/
            tv_prd_progress.setVisibility(View.GONE);
            /**撤销按钮**/
            btn_cancel.setVisibility(View.VISIBLE);
            /**申请金额|募集总额**/
            tv_raise_amount.setText(getString(R.string._raise_money));
            /**还款进度|借款期限**/
            tv_invset_money.setText(getString(R.string.loan_term, invest.getTerm()));
            /**下期还款日**/
            tv_next_term.setVisibility(View.GONE);
        } else if (TextUtils.equals(invest.applyprogress, "1")) {
            //风控审批中 显示还款方式，撤销按钮，申请金额，借款期限    ；隐藏：下期还款金额，募集状态，募集总额，还款进度，下期还款日
            /**设置还款方式**/
            tv_incomemonet.setVisibility(View.VISIBLE);
//            tv_incomemonet.setText(invest.getPayMethod(mContext));
            /**下期返款金额**/
            tv_next_amount.setVisibility(View.GONE);
            /**募集状态**/
            tv_prd_progress.setVisibility(View.GONE);
            /**撤销按钮**/
            btn_cancel.setVisibility(View.VISIBLE);
            /**申请金额|募集总额**/
            tv_raise_amount.setText(getString(R.string._raise_money));
            /**还款进度|借款期限**/
            tv_invset_money.setText(getString(R.string.loan_term, invest.getTerm()));
            /**下期还款日**/
            tv_next_term.setVisibility(View.GONE);
        } else if (TextUtils.equals(invest.applyprogress, "2")) {
            //运营审批中  显示还款方式，申请金额，借款期限    ；隐藏：下期还款金额，募集状态，撤销按钮，募集总额，还款进度，下期还款日
            /**设置还款方式**/
            tv_incomemonet.setVisibility(View.VISIBLE);
//            tv_incomemonet.setText(invest.getPayMethod(mContext));
            /**下期返款金额**/
            tv_next_amount.setVisibility(View.GONE);
            /**募集状态**/
            tv_prd_progress.setVisibility(View.GONE);
            /**撤销按钮**/
            btn_cancel.setVisibility(View.GONE);
            /**申请金额|募集总额**/
            tv_raise_amount.setText(getString(R.string._raise_money));
            /**还款进度|借款期限**/
            tv_invset_money.setText(getString(R.string.loan_term, invest.getTerm()));
            /**下期还款日**/
            tv_next_term.setVisibility(View.GONE);
        } else if (TextUtils.equals(invest.applyprogress, "10")) {
            //审批完成，已经转为产品  显示还款进度，募集总额，显示还款状态，下期还款时间，下期还款金额；   隐藏：还款方式，撤销按钮，申请金额，借款期限
            /**设置还款方式**/
            tv_incomemonet.setVisibility(View.GONE);
            /**下期返款金额**/
            tv_next_amount.setVisibility(View.VISIBLE);
            tv_next_amount.setText(getString(R.string.next_term_repayment,invest.next_repay_amt));

            /**下期还款日**/
            tv_next_term.setVisibility(View.VISIBLE);
            tv_next_term.setText(getString(R.string.next_term,invest.next_repay_day));

            /**募集状态**/
            tv_prd_progress.setVisibility(View.VISIBLE);
            //根据不同的募集状态，对ui进行相应的改变]

            /**  50和小于20的
             * 0	未发布	0：未发布
             10	投标中	1：投标中
             15	待放款	无
             18	放款中	无
             20	计息中	2：计息中
             30	待返还（暂时不用）	3：待返还
             40	已返还	4：已返还
             50	已结束	5：已结束
             60	已撤销	6：已结束
             100	逾期未返还
             105	逾期部分返还（暂不开发）
             110	逾期已返还
             120	流标
             125	停售（募集期截止但未募满）
             130	风控拒绝放款
             200	逾期已返还(与11重复废弃)
             */
            if (TextUtils.equals(invest.prdprogress,"0")){
                // TODO: 2017/5/26 未发布应该显示怎么样的ui
                tv_next_amount.setVisibility(View.GONE);
                tv_next_term.setVisibility(View.GONE);
                tv_incomemonet.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals(invest.prdprogress,"10")){
                // TODO: 2017/5/26 投标中显示的ui
                tv_next_amount.setVisibility(View.GONE);
                tv_next_term.setVisibility(View.GONE);
                tv_incomemonet.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals(invest.prdprogress,"15")){
                //待放款
                tv_next_amount.setVisibility(View.GONE);
                tv_next_term.setVisibility(View.GONE);
                tv_incomemonet.setVisibility(View.VISIBLE);
//                tv_incomemonet.setText(invest.getPayMethod(mContext));
            } else if (TextUtils.equals(invest.prdprogress,"18")){
                // TODO: 2017/5/26 放款中显示的ui
                tv_next_amount.setVisibility(View.GONE);
                tv_next_term.setVisibility(View.GONE);
                tv_incomemonet.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals(invest.prdprogress,"20")){
                // 计息中--待还款
                tv_next_amount.setVisibility(View.VISIBLE);
                tv_next_amount.setText(getString(R.string.next_term_repayment,invest.next_repay_amt));
                tv_next_term.setVisibility(View.VISIBLE);
                tv_next_term.setText(getString(R.string.next_term,invest.next_repay_day));
                tv_incomemonet.setVisibility(View.GONE);

            } else if (TextUtils.equals(invest.prdprogress,"30")){

            } else if (TextUtils.equals(invest.prdprogress,"40")){

            } else if (TextUtils.equals(invest.prdprogress,"50")){
                //已结束
                tv_next_amount.setVisibility(View.GONE);
                tv_next_term.setVisibility(View.GONE);
                tv_incomemonet.setVisibility(View.VISIBLE);

//                tv_incomemonet.setText(invest.getPayMethod(mContext));
            } else if (TextUtils.equals(invest.prdprogress,"60")){

            } else if (TextUtils.equals(invest.prdprogress,"100")){

            } else if (TextUtils.equals(invest.prdprogress,"105")){

            } else if (TextUtils.equals(invest.prdprogress,"120")){

            } else if (TextUtils.equals(invest.prdprogress,"125")){

            } else if (TextUtils.equals(invest.prdprogress,"130")){

            } else if (TextUtils.equals(invest.prdprogress,"200")){

            } else {
            }
            /**撤销按钮**/
            btn_cancel.setVisibility(View.GONE);
            /**申请金额|募集总额**/
            tv_raise_amount.setText(getString(R.string._raise_totle_amount));
            /**还款进度|借款期限**/
            tv_invset_money.setText(getString(R.string.repayment_schedule, invest.repayed_term + "/" + invest.total_term));

        } else if (TextUtils.equals(invest.applyprogress, "100")) {
            //用户撤回--不会有这种状态返回

        } else if (TextUtils.equals(invest.applyprogress, "110")) {
            //一审（风控）拒绝--不会有这种状态返回

        } else {
            //二审（运营）拒绝--不会有这种状态返回

        }
    }

    @Override
    public void onLoadMore() {
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.LOAN_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.LOAN_LIST,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.LOAN_LIST,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    public void onRefresh() {
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.LOAN_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.LOAN_LIST,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.LOAN_LIST,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position >= data.size()) return;
        Bundle bundle = new Bundle();
        //携带所有的数据过去
        bundle.putSerializable(Extras.DATA, data.get(position));
        readyGo(LoanDetailActivity.class, bundle);
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onItemClick(Object o, int position) {

    }
}

